﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.Core.Global;

namespace Common.Core.Cache
{
    public interface IMemoryCache
    {
        void SetKeyName(string keyName);
        T GetData<T>();
        T GetData<T>(string keyName);
        void SetData<T>(T t);
    }

    public class MemoryStorage : IMemoryCache
    {
        private string _KeyName;

        public void SetKeyName(string keyName)
        {
            _KeyName = keyName;
        }

        public T GetData<T>()
        {
            return (T)System.Web.HttpRuntime.Cache[_KeyName];
        }

        public T GetData<T>(string keyName)
        {
            return (T)System.Web.HttpRuntime.Cache[keyName];
        }

        public void SetData<T>(T t)
        {
            if (System.Web.HttpRuntime.Cache[_KeyName] == null)
            {
                System.Web.HttpRuntime.Cache.Add(_KeyName, t, null,
                System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(GlobalSetting.CacheInvalidTime, 0, 0),
                System.Web.Caching.CacheItemPriority.High,
                null);
            }
            else
            {
                System.Web.HttpRuntime.Cache[_KeyName] = t;
            }
        }
    }

    public class MemoryStorageManager<T, D> where T : IMemoryCache
    {
        private readonly IMemoryCache _obj;

        public MemoryStorageManager(IMemoryCache icahche)
        {
            _obj = icahche;
        }

        private static readonly MemoryStorageManager<T, D> _instance = new MemoryStorageManager<T, D>(default(T));

        public static MemoryStorageManager<T, D> Instance
        {
            get
            {
                return _instance;
            }
        }

        public D this[string index]
        {
            get
            {
                return _obj.GetData<D>(index);
            }
            set
            {
                _obj.SetData(value);
            }
        }
    }
}
